package com.study.service.impl;

import com.study.entity.User;
import com.study.mapper.TUserDAO;
import com.study.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Cacheable 指定 key 前缀, redis-cache-user:: + 方法中的 key
 */
@CacheConfig(cacheNames = "redis-cache-user")
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private TUserDAO userMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * @CacheEvict 删除缓存, key 默认是参数, 每次都执行
     */
    @Override
    @CacheEvict
    public int deleteByPrimaryKey(Integer id) {
        return userMapper.deleteByPrimaryKey(id);
    }

    /**
     * @CachePut 更新缓存, 每次都执行
     */
    @Override
    @CachePut(key = "#record.id")
    public User insertSelective(User record) {
        return userMapper.insertSelective(record) == 1 ? record : null;
    }

    /**
     * @Cacheable 开启缓存功能, 有就查询缓存, 没有就先查询 mysql 再放进缓存, 不一定执行
     */
    @Override
    @Cacheable
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }

    @Override
    @CachePut(key = "#record.id")
    public User updateByPrimaryKeySelective(User record) {
        return userMapper.updateByPrimaryKeySelective(record) == 1 ? record : null;
    }

    /**
     * 使用自定义 key
     */
    @Override
    @Cacheable(keyGenerator = "list")
    public List<User> listUser() {
        return userMapper.listUser();
    }

    /**
     * 删除所有缓存
     */
    @Override
    @CacheEvict
    public void clearCache() {
        stringRedisTemplate.delete(stringRedisTemplate.keys("redis-cache-user:*"));
    }
}
